#pragma once
#include <iostream>
#include <memory>
#include <string>
#include <poll.h>

#include "Log.hpp"
#include "Socket.hpp"

using namespace socket_ns;

// select 服务器需要正确编写，需要借助一个第三方数组来完成 保存合法的，所有的fd到数组中，方便后续批量化统一添加
class PollServer
{

    const static int gnum = 1024;
    const static int defaultfd = -1;
    const static int defaultevent = 0;

public:
    PollServer(int port)
        : _port(port),
          _listensock(std::make_unique<TcpSocket>()),
          _timeout(1000)
    {
        InetAddr addr("0", _port);
        _listensock->BuildListenSocket(addr);
        for (int i = 0; i < gnum; i++)
        {
            _events[i].fd = defaultfd;
            _events[i].events = defaultevent;
            _events[i].revents = defaultevent;
        }
        _events[0].fd = _listensock->SockFd();
        _events[0].events = POLLIN; // 表示对读事件关心(listensock 上有新连接，就是读时间)
    }
    void ServerIo(int pos)
    {
        char buffer[1024];
        ssize_t n = ::recv(_events[pos].fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            LOG(DEBUG, "获取新连接!\n");
            buffer[n] = 0;
            std::cout << "Client say# " << buffer << std::endl;
            std::string msg = "Server Echo# ";
            msg += buffer;
            send(_events[pos].fd, msg.c_str(), msg.size(), 0);
        }
        else if (n == 0)
        {
            LOG(DEBUG, "对方关闭连接!\n");
            ::close(_events[pos].fd);
            _events[pos].fd = defaultfd;
            _events[pos].events = _events[pos].revents = defaultevent;
        }
        else
        {

        }
    }
    void AcceptClient()
    {
        InetAddr addr;
        errno = 0;
        int sockfd = _listensock->Accepter(&addr, &errno);
        if (sockfd < 0)
        {
            return;
        }
        int i;
        for (i = 0; i < gnum; i++)
        {
            if (_events[i].fd == defaultfd)
                break;
        }

        if (i < gnum)
        {
            // 给poll添加新的sockfd
            LOG(DEBUG, "获取新链接\n");
            _events[i].fd = sockfd;
            _events[i].events = POLLIN;
            _events[i].revents = defaultevent;
        }
        else
        {
            LOG(WARNING, "数组满了\n");
            ::close(sockfd);
        }
    }

    void HandlerEvents()
    {
        for (int i = 0; i < gnum; i++)
        {
            if (_events[i].fd == defaultfd)
                continue;

            int fd = _events[i].fd;
            uint16_t revent = _events[i].revents;

            if (revent & POLLIN)
            {
                if (fd == _listensock->SockFd())
                {
                    AcceptClient();
                }
                else
                {
                    ServerIo(i);
                }
            }

            if (revent & POLLOUT)
            {
                // TODO
            }
        }
    }

    void Loop()
    {
        while (true)
        {
            int n = poll(_events, gnum, -1);
            switch (n)
            {
            case 0:
                // LOG(INFO, "timeout ....[ %d ]:[ %d ]\n", timeout.tv_sec, timeout.tv_usec);
                LOG(INFO, "timeout ....\n");
                break;
            case -1:
                LOG(ERROR, "poll serror ....\n");
                break;
            default:
                LOG(DEBUG, "Event Happen! ....就绪的文件描述符个数[ %d ]\n", n);
                HandlerEvents();
                break;
            }
        }
    }

    std::string PrintDebug()
    {
        std::string fdstr;
        for (int i = 0; i < gnum; i++)
        {
            if (_events[i].fd == defaultfd)
                continue;
            fdstr += std::to_string(_events[i].fd);
            fdstr += " ";
        }
        return fdstr;
    }

    ~PollServer()
    {
    }

private:
    uint32_t _port;
    std::unique_ptr<Socket> _listensock;
    struct pollfd _events[gnum];
    int _timeout;
};
